package admin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminResourceDel(ctx context.Context, pb *pbAdmin.AdminResourceDelReq) (*pbAdmin.AdminResourceDelResp, error) {

	if len(pb.Id) < 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.ErrorfByErrorInfo(businessError.ParamsInvalid, "id参数不能为空"))
	}
	Db := database.Db.GetDefaultDb(ctx)
	rows, dbErr := Db.Query("select * from admin_resource")

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	t := utils.NewTree().Init(rows)

	ChildrenIds := []interface{}{}

	for _, id := range pb.Id {
		ChildrenIds = append(ChildrenIds, t.GetChildrenIds(id, true)...)
	}

	if len(ChildrenIds) == 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.Error(businessError.OperateError.Code, "id参数不能为空"))
	}

	rowCount, dbErr := Db.Delete("admin_resource", map[string]interface{}{
		"id": ChildrenIds,
	})

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	if rowCount <= 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.OperateError)
	}

	return &pbAdmin.AdminResourceDelResp{
		RowCount: rowCount,
	}, nil
}
